package backend

import (
	"blog/model"
	"blog/service/page"
	"net/http"
	"time"

	"gitee.com/xchengli/blog-lib/components"
	"gitee.com/xchengli/blog-lib/database"
	"gitee.com/xchengli/blog-lib/session"
	"gitee.com/xchengli/blog-lib/zlog"

	"github.com/gin-gonic/gin"
)

// Login 管理员登录
func Login(ctx *gin.Context) {
	// 调用 ps 层
	adminUserPageService := page.NewAdminUserPageService()
	adminUser, err := adminUserPageService.CheckLogin(ctx, ctx.PostForm("userName"), ctx.PostForm("userPass"))
	if err != nil {
		zlog.Error(ctx, err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "登录失败: " + err.Error()})
		return
	}

	//用户状态检查
	if adminUser.Status == -1 {
		zlog.Error(ctx, "用户被禁用")
		ctx.JSON(http.StatusForbidden, gin.H{"error": "用户被禁用"})
		return
	}

	// 创建登录记录
	sessionID := components.GetRandomString(32)

	// 直接创建 AdminLogin 结构体
	AL := model.AdminLogin{
		Key:        sessionID,
		UID:        adminUser.ID,
		Status:     1,
		LoginFrom:  1,
		LoginIP:    components.GetClientIP(ctx.Request),
		UserAgent:  ctx.Request.UserAgent(),
		CreateTime: time.Now(),
	}

	// 直接使用数据库创建登录记录
	db := database.GetDB()
	AL.CreateTime = time.Now()
	AL.UpdateTime = time.Now()
	err = db.Create(&AL).Error
	if err != nil {
		zlog.Error(ctx, err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "记录登陆日志失败" + err.Error()})
		return
	}

	// 设置Session
	guest := &session.GuestSession{}
	guest.Key = sessionID
	guest.UID = adminUser.ID
	guest.Name = adminUser.Name
	guest.Email = adminUser.Email
	guest.Status = int(adminUser.Status)
	err = guest.SetSession()
	if err != nil {
		zlog.Error(ctx, err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "写入Session失败:" + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"message": "登录成功"})
}

// Logout 管理员退出登录
func Logout(ctx *gin.Context) {
	guest := &session.GuestSession{}
	guest.Init(ctx.Request)

	if !guest.CheckIsLogin() {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
		return
	}

	err := guest.Delete()
	if err != nil {
		zlog.Error(ctx, err)
		ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Session写入失败"})
		return
	}

	//修改状态
	db := database.GetDB()
	err = db.Model(&model.AdminLogin{}).Where("key = ?", guest.GetGuestId()).Update("status", 0).Error
	if err != nil {
		zlog.Error(ctx, err)
	}
	ctx.JSON(http.StatusOK, gin.H{"message": "退出登录"})
}
